# -*- coding:utf-8 -*-
import base64
import json
import random

from jinja2 import Environment, PackageLoader

from util.email_sender import EmailSender
from util.redis_connect import RedisPoolConnect

# 缓存连接池
REDIS_POOL_EMAIL = RedisPoolConnect(0)
# 获取邮件模板
ENV = Environment(loader=PackageLoader('email_template', 'templates'))
TEMPLATE = ENV.get_template('email.html')

EMAILSENDER = EmailSender()


def handler(event, context):
    logger = context.getLogger()
    messages = event.get("records")[0].get("messages")
    for message in messages:
        logger.info(message)
        message = json.loads(message)
        contact = message.get("contact")
        verify_id = message.get("verifyId")
        user_name = message.get("userName")
        verification_code = "".join([str(random.randint(0, 9)) for i in range(6)])
        # jinja2模板渲染
        email_html = TEMPLATE.render(verification_code=verification_code)
        EMAILSENDER.send_email(contact, email_html)
        key = f"{verify_id}+{user_name}"
        REDIS_POOL_EMAIL.set_key_value(key, verification_code)
